<?php
namespace App\Api\Controllers\Lianhou;


use App\Models\YinkaStore;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Rtgm\sm\RtSm4;
use Rtgm\sm\RtSm2;

use phpseclib\Crypt\RSA;
use phpseclib\Crypt\Hash;

class BaseController
{
    static $config, $instance, $data;

    const MAIN_URL ='https://smf.jingweitech.cn:8443/';
    const QR_SUBMIT = 'api/trade/cashierPreOrder.html';

    const SCAN_PAY = 'api/trade/passiveScanOrder.html';

    const QUERY_ORDER = 'api/trade/queryPayOrder.html';

    const REFUND = 'api/trade/refund.html';

    public static function getInstance ()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function params ($request, $config)
    {
        $params['nonce'] = time();
        $params['agentCode'] = $config->platform_id; //平台商户号
        $params['reqData'] = stripslashes(json_encode($request, JSON_UNESCAPED_UNICODE));
        $params['sign'] = $this->ASCIISHA256($params, $config->sign_key);

        $params['reqData'] = $this->encryptStr(stripslashes(json_encode($request, JSON_UNESCAPED_UNICODE)), $config->key);
        self::$data = $params;
        return $this;
    }

    /**
     * ASCII排序
     * @param array $params
     * @param $key
     * @return bool|string
     */
    public function ASCIISHA256($params = array(), $key)
    {
        if (!empty($params)) {
            $params = array_filter($params);
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $val = trim($val);
                    if ($val === '' || $val === null) {
                        continue;
                    }
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                $stringSignTemp = $strs . '&key=' . $key;


                $re = hash('sha256', $stringSignTemp, true);
                return strtoupper(bin2hex($re));
            }
        }
        return false;
    }


    /**
     * des 加密
     * str 需要加密的账号
     * key 加密秘钥
     */
    public function encryptStr($str, $key)
    {
        $data = mb_convert_encoding($str, 'UTF-8');
        $encry = openssl_encrypt($data, 'DES-ECB', $key, OPENSSL_RAW_DATA);
        return base64_encode($encry);
    }

    /**
     * 解密
     */
    public function decryptStr($data, $key)
    {
        $decry = openssl_decrypt(base64_decode($data), 'DES-ECB', $key, OPENSSL_RAW_DATA);
        return $decry;
    }

    public function build ($url, $config, $fun)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::MAIN_URL.$url); //设置选项，包括URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);


        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(self::$data));

        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Charset: UTF-8';
        $headers[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $output = curl_exec($ch); //执行并获取HTML文档内容

        curl_close($ch); //释放curl句柄


        Log::channel("lianhou")->info($fun."_Request", self::$data);

        $output = json_decode($output, true);
        Log::channel("lianhou")->info($fun."_Response", $output);
        if (isset($output['respData'])) {
            $output = $this->decryptStr($output['respData'], $config->key);
            $output = json_decode($output, true);
            Log::channel("lianhou")->info($fun."_Response", $output);
        }
        return $output;

    }

}